/*
 * Copyright 2019 xiaomaoguai.com All right reserved. This software is the
 * confidential and proprietary information of xiaomaoguai.com ("Confidential
 * Information"). You shall not disclose such Confidential Information and shall
 * use it only in accordance with the terms of the license agreement you entered
 * into with xiaomaoguai.com.
 */

package com.xiaomaoguai.core.next.nacos.discovery;

import app.myoss.cloud.core.constants.DeployEnvEnum;
import com.alibaba.cloud.nacos.ConditionalOnNacosDiscoveryEnabled;
import com.alibaba.cloud.nacos.NacosDiscoveryAutoConfiguration;
import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.context.annotation.Configuration;

import java.util.Map;

import static com.xiaomaoguai.core.next.nacos.constants.NacosDiscoveryConstants.ENV_SERVICE_TAGS;
import static com.xiaomaoguai.core.next.nacos.constants.NacosDiscoveryConstants.META_SERVICE_DOMAIN;

/**
 * Nacos服务发现自动配置
 *
 * @author chenyao
 * @since 2019年6月20日 上午8:54:03
 * @see com.alibaba.cloud.nacos.NacosDiscoveryAutoConfiguration
 */
@Configuration
@ConditionalOnNacosDiscoveryEnabled
@AutoConfigureBefore({ NacosDiscoveryAutoConfiguration.class })
public class ZaNacosDiscoveryAutoConfiguration {
    /**
     * Nacos服务发现自动配置
     *
     * @param nacosDiscoveryProperties Nacos服务发现配置属性
     */
    public ZaNacosDiscoveryAutoConfiguration(NacosDiscoveryProperties nacosDiscoveryProperties) {
        String serviceTags = StringUtils.defaultIfBlank(System.getProperty(ENV_SERVICE_TAGS),
                System.getenv(ENV_SERVICE_TAGS));
        if (!DeployEnvEnum.isDev() && StringUtils.isNotBlank(serviceTags)) {
            String suffix = "." + DeployEnvEnum.getDeployEnv() + ".za.biz";
            String serverDomain = serviceTags.replaceAll("_", "-").substring(0, serviceTags.length() - 2) + suffix;
            Map<String, String> metadata = nacosDiscoveryProperties.getMetadata();
            metadata.put(META_SERVICE_DOMAIN, serverDomain);
        }
    }
}
